<?php

namespace service;

use app\common\model\Log;
use app\common\model\Member;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;

class AuthH5
{

    protected static $instance = null;
    protected $_error = '';
    protected $_logined = FALSE;
    protected $_user = NULL;
    protected $_token = '';
    //Token默认有效时长
    protected $keeptime = 25920000;
    protected $requestUri = '';
    protected $rules = [];
    //默认配置
    protected $config = [];
    protected $options = [];
    protected $allowFields = ['id','nickname', 'headimgurl','token','sex','referer_code','coin_balance'];

    public function __construct($options = [])
    {
        $this->options = array_merge($this->config, $options);
    }

    /**
     *
     * @param array $options 参数
     * @return AuthH5
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 兼容调用user模型的属性
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->_user ? $this->_user->$name : NULL;
    }

    /**
     * 根据Token初始化
     *
     * @param string $token Token
     * @return boolean
     */
    public function init($token)
    {
        if ($this->_logined) {
            return true;
        }
        if ($this->_error) {
            return false;
        }
        $data = Token::get($token);
        if (!$data) {
            return false;
        }
        $user_id = intval($data['user_id']);
        if ($user_id > 0) {
            $user = Member::get($user_id);
            if (!$user) {
                return false;
            }
            $user->uid = $user->id;
            $this->_user    = $user;
            $this->_logined = true;
            $this->_token   = $token;
            return true;
        } else {
            return false;
        }
    }

    /**
     * 微信快速注册
     * @param string $WXUserInfo 微信用户信息
     * @return boolean
     */
    public function quickLogin($WXUserInfo)
    {
        $user = Member::where('unionid', $WXUserInfo['unionid'])->find();
        //直接登录会员
        if ($user) {
            $this->direct($user , $WXUserInfo);
        } else {
            $WXUserInfo['user_type'] = Member::WECHAT_H5_USER;
            $WXUserInfo['h5_openid'] = $WXUserInfo['openid'];
            $this->register($WXUserInfo);
        }
        return true;
    }

    /**
     * 手机号注册
     * @param string $moblie 口红机用户登录信息
     * @return boolean
     */
    public function mobileLogin($data)
    {
        $user = Member::where('mobile', $data['mobile'])->find();
        //直接登录会员
        if ($user) {
            $this->direct($user);
        } else {
            $data['nickname'] = $data['mobile'];
            $data['headimgurl'] = '/static/h5/img.png';
            $data['user_type'] = Member::MOBILE_H5_USER;
            $this->register($data);
        }
        return true;
    }

    /**
     * 注册用户
     * @param string $WXUserInfo 微信用户信息
     * @return boolean
     */
    public function register($data)
    {
        $user = Member::create($data);
        // 邀请逻辑 每天最多邀请10人
        if(isset($data['ref']) && !empty($data['ref'])) {
            $this->add_coin($data['ref']);
        }
        $this->direct($user);
        return true;
    }

    /**
     * 为用户增加游戏币
     * @param $ref
     */
    public function add_coin($ref = ''){
        if($ref == '') return false;

        $user_info = Member::getByRefererCode($ref);
        if($user_info) {
            $time_start = strtotime(date('Y-m-d', time()). '23:59:59');
            $time_end = strtotime(date('Y-m-d', time()));
            $invite_count = Member::where('ref', $ref)->whereBetween('create_time', [$time_start, $time_end])->count();
            if($invite_count < 10) {
                Member::where('referer_code', $ref)->setInc('coin_balance', Member::INVITE_COIN);
                $log = [
                    'uid' => $user_info->id,
                    'money' => Member::INVITE_COIN,
                    'type' => 4,
                    'status' => 11,
                ];
                Log::create($log);
            }
        }
    }
    /**
     * 直接登录账号
     * @param int $user 用户信息
     * @param int $WXUserInfo 微信用户信息
     * @return boolean
     */
    public function direct($user , $WXUserInfo = '')
    {
        if (!$user) {
            return false;
        }
        //判断连续登录和最大连续登录
        $token = Random::uuid();
        //记录本次登录的IP和时间
        $user->last_ip  = request()->ip();
        $user->login_at = time();
        $user->token    = $token;
        if(empty($user->referer_code)){
            $user->referer_code = get_ref($user->id);
        }
        if($WXUserInfo != false){
            $user->h5_openid  = $WXUserInfo['openid'];
            $user->nickname  = $WXUserInfo['nickname'];
            $user->sex       = $WXUserInfo['sex'];
            $user->city      = $WXUserInfo['city'];
            $user->province  = $WXUserInfo['province'];
            $user->country   = $WXUserInfo['country'];
            $user->headimgurl = $WXUserInfo['headimgurl'];
            $user->privilege = json_encode($WXUserInfo['privilege']);
            $user->access_token = $WXUserInfo['access_token'];
            $user->refresh_token = $WXUserInfo['refresh_token'];
        }
        $user->save();

        $this->_token = $token;
        $this->_user  = $user;
        Token::set($this->_token, $user->id, $this->keeptime);
        $this->_logined = true;

        $this->keeplogin();
        //登录成功的事件
        return true;
    }

    /**
     * 判断是否登录
     * @return boolean
     */
    public function isLogin()
    {
        if ($this->_logined) {
            return true;
        }
        return false;
    }

    public function isUserType()
    {
        return $this->_usertype;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin($token)
    {
        $keeplogin = Cookie::get(Config::get('keeplogin'));
        if (!$keeplogin) {
            return false;
        }
        list($user_id, $keeptime, $expiretime, $key) = implode('|', $keeplogin);
        if ($user_id && $keeptime && $expiretime && $key && $expiretime > time()) {
            $user = Member::get($user_id);
            if (!$user) {
                return false;
            }
            //token有变更
            if ($key != md5(md5($user_id) . md5($keeptime) . md5($expiretime) . $token)) {
                return false;
            }
            //刷新自动登录的时效
            $this->keeplogin($keeptime);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取当前Token
     * @return string
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * 刷新保持登录的Cookie
     *
     * @param   int $keeptime
     * @return  boolean
     */
    protected function keeplogin($keeptime = 86400)
    {
        $data = Token::get($this->_token);
        if (time() > $data['expiretime']) {
            $expiretime = time() + $keeptime;
            $key        = md5(md5($data['user_id']) . md5($data['user_type']) . md5($keeptime) . md5($expiretime) . $data['token']);
            $param      = [$data['user_id'], $data['user_type'], $keeptime, $expiretime, $key];
            Cookie::set(Config::get('keeplogin'), implode('|', $param), 86400 * 30);
            return true;
        }
        return false;
    }

    /**
     * 获取会员基本信息
     */
    public function getUserinfo()
    {
        $data        = $this->_user->toArray();
        $allowFields = $this->getAllowFields();
        $userinfo    = array_intersect_key($data, array_flip($allowFields));
//        $userinfo    = array_merge($userinfo, Token::get($this->_token));
        $userinfo['token'] = $this->_token;
        return $userinfo;
    }


    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

    /**
     * 获取允许输出的字段
     * @return array
     */
    public function getAllowFields()
    {
        return $this->allowFields;
    }

    /**
     * 设置允许输出的字段
     * @param array $fields
     */
    public function setAllowFields($fields)
    {
        $this->allowFields = $fields;
    }


    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr     = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return FALSE;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return TRUE;
        }
        // 没找到匹配
        return FALSE;
    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $expiretime = time() + $keeptime;
        $key        = md5(md5($this->_user['user_id']) . md5($keeptime) . md5($expiretime) . $this->_token);
        $data       = [$this->id, $keeptime, $expiretime, $key];
        Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
        return true;
    }

    /**
     * 渲染用户数据
     * @param array $datalist 二维数组
     * @param mixed $fields 加载的字段列表
     * @param string $fieldkey 渲染的字段
     * @param string $renderkey 结果字段
     * @return array
     */
    public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
    {
        $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
        $ids    = [];
        foreach ($datalist as $k => $v) {
            if (!isset($v[$fieldkey]))
                continue;
            $ids[] = $v[$fieldkey];
        }
        $list = [];
        if ($ids) {
            if (!in_array('id', $fields)) {
                $fields[] = 'id';
            }
            $ids        = array_unique($ids);
            $selectlist = Users::where('id', 'in', $ids)->column($fields);
            foreach ($selectlist as $k => $v) {
                $list[$v['id']] = $v;
            }
        }
        foreach ($datalist as $k => &$v) {
            $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : NULL;
        }
        unset($v);
        return $datalist;
    }

    /**
     * 设置错误信息
     *
     * @param $error 错误信息
     * @return AuthH5
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? $this->_error : '';
    }

}
